package Day2025_03_13;

public class LeeCode188 {
    public int maxProfit(int k, int[] p) {
        int n = p.length;
        int INF = -0x3f3f3f;
        int[][] f = new int[n][k + 1];
        int[][] g = new int[n][k + 1];
        for (int i = 0; i < k + 1; i++) {
            f[0][i] = INF;
            f[0][i] = INF;
        }
        f[0][0] = -p[0];
        g[0][0] = 0;
        for (int i = 1; i < n ; i++) {
            for (int j = 0; j < k + 1; j++) {
                f[i][j] = Math.max(g[i - 1][j] - p[i], f[i - 1][j]);
                g[i][j] = g[i - 1][j];
                if (j - 1 >= 0) g[i][j] = Math.max(f[i - 1][j - 1] + p[i], g[i][j]);
            }
        }
        int ret = 0;
        for (int i = 0; i < k + 1; i++) {
            ret = Math.max(ret, g[n - 1][i]);
        }
        return ret;
    }
}
